const puppeteer = require('puppeteer');
const fs = require('fs');

let totalBlogs = [];
let errLogs = [];

async function main() {
  let sub_url = '';
  let tab = 'gitchat';
  let sub_tab = '通用';
  const fileName = `${tab}_${sub_tab}.json`;
  let totalBlogs = [];

  const browser = await puppeteer.launch({
    // executablePath: '/Users/yinhaixiang/develop/chromium/Chromium.app/Contents/MacOS/Chromium',
    headless: false,
    slowMo: 0,
    args: ['--no-sandbox', '--user-data-dir=/Users/yinhaixiang/develop/data/session-xxx'],
    ignoreDefaultArgs: ['--enable-automation']
  });
  const page = (await browser.pages())[0];
  await page.setViewport({width: 1500, height: 0});

  page.on('pageerror', msg => {
    console.log(msg);
  });

  let url = `https://gitbook.cn/gitchat/activity/5d1d6171bdaa30360df3b138`;
  await page.goto(url, {waitUntil: 'domcontentloaded'});
  // await page.click('#loginBtn2');

  let real_url = null;

  try {
    await page.click('#activityOrderPayBtn');
    await page.waitForNavigation();
    real_url = await page.$eval('#activityOrderBtn', el => el.href);
  } catch (e) {
    console.log('进入catch...');
    await page.click('#activityOrderBtn');
    real_url = page.url();
  }

  console.log(real_url);


};


async function collectBlogs(page, tab, subTab) {
  let blogs = await page.$$eval('#chatItemContainer > div.chat_list > a', async (eles, tab, sub_tab) => {
    let tmpBlogs = [];
    eles.forEach(async ele => {
      let title = ele.querySelector('h2').innerText;
      let content = ele.href;
      let source = ele.querySelector('div.chat_item_bottom > span').innerText.replace(/·.+/, '').trim();
      tmpBlogs.push({
        title: title,
        content: content,
        tab: tab,
        sub_tab: sub_tab,
        source: source
      });
    });
    return tmpBlogs;
  }, tab, subTab);
  return blogs;
}

main();


